import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { Modal, Button, Empty, Tooltip, message, Icon } from 'antd';
import cn from 'classnames';
import { TASK_TYPE_MAP, TASK_PRIORITY_MAP } from '@util/constants';
import './index.less';
import getRealTime from '@util/get-real-time';
import moment from 'moment';
import { List } from 'react-virtualized';
import _ from 'lodash';
import { downloadDict } from '@api/dict';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import { getDetailOnedayList } from '@api/task';
import copyImg from '@images/new_copy.svg';
import copyToClipboard from '@util/copy-to-clipboard';

const Info = props => {
  const { task = {}, history } = props;
  const params = _.get(task, 'taskParams.onedayTaskParams', {});

  let fakeScanType = _.get(params, 'isWeakPassTask') ? 'WeakPassword' : 'OneDay';

  const [visibleMoreModal, setVisibleMoreModal] = useState('');
  const [pagination, setPagination] = useState({ page: 1, pageSize: 100 });
  const [countList, setCountList] = useState(0);
  const [list, setList] = useState('');
  const [strategyModel, setStrategyModel] = useState(false);
  const OnedayList = (type = 'all') => {
    getDetailOnedayList({
      type: type,
      taskId: task._id,
      roundId: task.round_id,
      page: pagination.page,
      pageSize: pagination.pageSize
    }).then(r => {
      const { count, list } = r.data.data;
      setCountList(count);
      setList(list);
    });
  };

  const clear = () => {
    setPagination({ page: 1, pageSize: 100 });
    setList([]);
  };

  const Copy = () => {
    getDetailOnedayList({
      type: 'all',
      taskId: task._id,
      roundId: task.round_id
    }).then(r => {
      const { count, list } = r.data.data;
      setCountList(count);
      setList(list);
      const res = copyToClipboard(list);
      res ? message.success('复制成功') : message.error('复制失败');
    });
  };

  const titleModal = () => {
    return (
      <span>
        检测策略({countList})个
        <Tooltip title={'检测策略最多显示100个,您可通过复制按钮将全部检测策略名称复制出来'}>
          <Icon
            type="exclamation-circle"
            style={{ verticalAlign: 'text-bottom', marginLeft: '5px' }}
          />
        </Tooltip>
      </span>
    );
  };

  useEffect(() => {
    if (task._id) {
      OnedayList('part');
    }
  }, [task, pagination.page, strategyModel]);
  const count = _.get(task, 'round', 1);
  const priority = TASK_PRIORITY_MAP[_.get(task, 'taskParams.priority')] || '-';
  // 下轮执行时间
  const timing = _.get(task, 'taskParams.timing', {});
  let predictNextStartAt = '-';
  if (_.get(task, 'isCycle')) {
    const lastEnd = _.get(task, 'lastEnd');
    const interval = _.get(task, 'intervalTime');
    const unit = `${_.get(task, 'intervalUnit')}`;
    const status = _.get(task, 'status');
    const endAt = _.get(timing, 'endAt');
    // 预计下轮开始时间不能超出设置的任务执行时限
    if (
      lastEnd &&
      interval &&
      unit &&
      !['paused', 'stopped'].includes(status) &&
      (endAt ? moment(lastEnd).add(interval, unit) < moment(endAt) : true)
    ) {
      predictNextStartAt = moment(lastEnd)
        .add(interval, unit)
        .format('YYYY-MM-DD HH:mm:ss');
    }
  }
  // 任务执行时间段
  const timingStartAndEnd =
    _.get(timing, 'startAt') && _.get(timing, 'endAt')
      ? `${_.get(timing, 'startAt')} 至 ${_.get(timing, 'endAt')}`
      : _.get(timing, 'startAt')
      ? `任务须在${_.get(timing, 'startAt')}以后开始`
      : _.get(timing, 'endAt')
      ? `任务须在${_.get(timing, 'endAt')}以前结束`
      : '不限制';
  const lastEnd = _.get(task, 'lastEnd') ? moment(task.lastEnd).format('YYYY-MM-DD HH:mm:ss') : '';
  const status = _.get(task, 'taskParams.status');
  const recentEndTime = !['processing', 'paused'].includes(status) && lastEnd;
  const lastStart = _.get(task, 'lastStart');
  const pendingTime = _.get(task, 'pendingTime');
  let detectionTime = '-';
  let lastStartTIme = _.get(task, 'lastStart');
  if (status === 'finished') {
    detectionTime = getRealTime(lastStartTIme, lastEnd, pendingTime, 'done');
  }
  const timingDailyStartAndEnd =
    _.get(task, 'taskParams.timing.dailyStart') && _.get(task, 'taskParams.timing.dailyEnd')
      ? `${_.get(task, 'taskParams.timing.dailyStart')} 至 ${_.get(
          task,
          'taskParams.timing.dailyEnd'
        )}`
      : '-';

  const downloadFile = fileName => {
    downloadDict({ fileName })
      .then(() => {
        message.success('下载成功！');
      })
      .catch(() => {
        message.error('下载失败！');
      });
  };

  let details = [];

  if (fakeScanType === 'OneDay') {
    // 等待未开启任务时server读的详情taskParams的数据，并且值为whiteList,调度返回的WHITELIST
    let ignoreType = _.get(task, 'taskInfo.ignoreType') || _.get(task, 'taskParams.ignoreType');
    details = [
      [
        '禁扫目标',
        ignoreType?.find(r => ['WHITELIST', 'whiteList'].includes(r)) ? (
          <span>
            启用&nbsp;&nbsp;&nbsp;&nbsp;<Link to={'/asset-config/white-list'}>查看详情</Link>
          </span>
        ) : (
          '禁用'
        )
      ],
      ['优先级', priority],
      ['定时设置', timingStartAndEnd],
      ['每日允许时间段', timingDailyStartAndEnd],
      [<div key="repeat">探测轮次</div>, `${count}次`],
      ['最近一次开始时间', lastStart || '-'],
      ['最近一次结束时间', lastEnd || '-'],
      ['最近一次检测耗时', detectionTime],
      ['预计下轮开始时间', predictNextStartAt]
    ];
  } else if (fakeScanType === 'WeakPassword') {
    details = [
      [
        '禁扫目标',
        _.get(task, 'taskInfo.ignoreType', []).includes('WHITELIST') ? (
          <span>
            启用&nbsp;&nbsp;&nbsp;&nbsp;<Link to={'/asset-config/white-list'}>查看详情</Link>
          </span>
        ) : (
          '禁用'
        )
      ],
      ['优先级', priority],
      ['定时设置', timingStartAndEnd],
      ['每日允许时间段', timingDailyStartAndEnd],
      [<div key="repeat">探测轮次</div>, `${count}次`],
      [
        '用户名字典',
        <div key="v0">
          <Button
            type={'link'}
            disabled={_.get(params, 'isCustomUsernameDictDeleted')}
            onClick={() => downloadFile(_.get(params, 'usernameDictFileName'))}
          >
            下载
          </Button>
        </div>
      ],
      [
        '密码字典',
        <div key="v1">
          <Button
            type={'link'}
            disabled={_.get(params, 'isCustomPasswordDictDeleted')}
            onClick={() => downloadFile(_.get(params, 'passwordDictFileName'))}
          >
            下载
          </Button>
        </div>
      ],
      ['最近一次开始时间', lastStart || '-'],
      ['最近一次结束时间', recentEndTime || '-'],
      ['最近一次检测耗时', detectionTime],
      ['预计下轮开始时间', predictNextStartAt]
    ];
  }

  let targets = [],
    onedays = [];
  if (
    ['custom', 'siteIdList', ' affectedByTarget', 'targetGroup'].includes(
      _.get(params, 'target.queryType')
    )
  ) {
    targets.push(..._.get(params, 'target.showList', []).slice(0, 10));
  } else if (_.get(params, 'target.count', 0) !== 0) {
    targets.push(_.get(params, 'target.description'));
  }
  if (!targets.length) {
    targets.push('目标已被删除');
  }

  if (
    _.get(params, 'oneday.queryType') === 'list' ||
    _.get(params, 'oneday.queryType') === 'template'
  ) {
    onedays.push(..._.get(params, 'oneday.showList', []));
  } else if (_.get(params, 'oneday.description')) {
    onedays.push({
      name: _.get(params, 'oneday.description', ' '),
      isModules: false
    });
  }
  const modalDataMap = {
    targets: targets,
    onedays: onedays,
    usernames: _.get(params, 'usernames', []),
    passwords: _.get(params, 'passwords', [])
  };

  const isAllAssets =
    _.get(params, 'target.description') === '全部资产' && _.get(params, 'target.count') === 0;
  const targetCount = !isAllAssets
    ? _.get(params, 'target.count', 0)
    : _.get(task, 'targetCount', 0);
  const isCustom =
    _.get(params, 'oneday.count') === -1 || _.get(params, 'oneday.description') === '受影响插件';
  const titlesMap = {
    targets: `检测目标 (${targetCount})个`,
    usernames: `用户名字典 (${_.get(task, 'onedayTaskParams.usernames.length')})个`,
    passwords: `密码字典 (${_.get(task, 'onedayTaskParams.passwords.length')})个`,
    onedays: isCustom ? '检测策略' : `检测策略 (${_.get(params, 'oneday.count', 0)})个`
  };

  // eslint-disable-next-line
  const Targets = ({ type, items = [], width, className }) => {
    return (
      <div className={cn('ip-port-item', className)}>
        <div className="title">
          <span className="name">{titlesMap[type]}</span>
          {!isCustom && (
            <span
              className="show-more"
              onClick={() => {
                if (type === 'onedays') {
                  setStrategyModel(true);
                  return;
                }
                setVisibleMoreModal(type);
              }}
            >
              查看更多
            </span>
          )}
        </div>
        <div className="items">
          {items.map((item, index) => {
            return (
              <Tooltip key={index} title={item.name || item}>
                <div
                  className="item"
                  style={{ width }}
                  onClick={() => {
                    item.isModules
                      ? history.push({
                          pathname: '/asset-config/strategy-template',
                          query: { name: item.name }
                        })
                      : null;
                  }}
                >
                  {item.name || item}
                </div>
              </Tooltip>
            );
          })}
          {items.length === 0 && (
            <Empty style={{ width: '100%' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </div>
      </div>
    );
  };

  const moreModalFooter = [
    <Button type="primary" onClick={() => setVisibleMoreModal('')} key="0">
      关闭
    </Button>
  ];

  const strategyMoreModalFooter = [
    <Button
      type="primary"
      onClick={() => {
        setStrategyModel(false), clear();
      }}
      key="0"
    >
      关闭
    </Button>
  ];

  return (
    <div className="tmd-c-info">
      <div className="title">
        <span className="name">{_.get(task, 'taskParams.name', '-')}</span>
        <span className="type">{TASK_TYPE_MAP[fakeScanType]}任务</span>
      </div>
      <div className="content">
        <div className="ip-port">
          <Targets type="targets" items={targets} />
          <Targets type="onedays" items={onedays} />
          <br />
          <div className="details">
            {details.splice(0, 2).map((detail, index) => {
              return (
                <div className="detail-item" key={index}>
                  <span className="label">{detail[0]}</span>
                  <div className="value">{detail[1]}</div>
                </div>
              );
            })}
          </div>
        </div>
        <div className="details">
          {details.map((detail, index) => {
            return (
              <div className="detail-item" key={index}>
                <span className="label">{detail[0]}</span>
                <div className="value">{detail[1]}</div>
              </div>
            );
          })}
        </div>
      </div>
      <Modal
        maskClosable={false}
        visible={Boolean(visibleMoreModal)}
        title={titlesMap[visibleMoreModal] || ''}
        onCancel={() => setVisibleMoreModal('')}
        className={cn('more-ip-ports', 'no-header-bottom-lines', 'bottom-center', 'padding-24')}
        footer={moreModalFooter}
      >
        <div className="items">
          {_.get(modalDataMap, [visibleMoreModal, 'length']) ? (
            <List
              width={472}
              height={230}
              rowCount={modalDataMap[visibleMoreModal].length}
              rowRenderer={({ index, key, style }) => {
                let item = get(modalDataMap, `${visibleMoreModal}.${index}`, '');
                style.width = 'auto';
                style.marginLeft = '100px';
                style.paddingBottom = '8px';
                return (
                  <Tooltip title={item.name || item} key={key}>
                    <div style={style}>
                      <div className="item">{item.name || item}</div>
                    </div>
                  </Tooltip>
                );
              }}
              rowHeight={33}
              overscanRowCount={10}
            />
          ) : (
            <div className="empty">
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            </div>
          )}
        </div>
      </Modal>
      <Modal
        maskClosable={false}
        visible={strategyModel}
        title={titleModal()}
        onCancel={() => setStrategyModel(false)}
        className={cn('more-strategy', 'no-header-bottom-lines', 'bottom-center', 'padding-24')}
        footer={strategyMoreModalFooter}
      >
        <div className="items">
          {_.get(list, 'length') ? (
            <>
              <img src={copyImg} className={'copy-img'} onClick={Copy} />
              <List
                width={472}
                height={330}
                rowCount={list.length}
                rowRenderer={({ index, key, style }) => {
                  let item = get(list, `${index}`, '');
                  style.width = 'auto';
                  style.marginLeft = '50px';
                  style.paddingBottom = '8px';
                  return (
                    <Tooltip title={item.name || item} key={key}>
                      <div style={style}>
                        <div className="item">{item.name || item}</div>
                      </div>
                    </Tooltip>
                  );
                }}
                rowHeight={33}
                overscanRowCount={10}
              />
            </>
          ) : (
            <div className="empty">
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

Info.propTypes = {
  task: PropTypes.object,
  history: PropTypes.object
};

export default withRouter(Info);
